package cn.itcast.avro;

import cn.itcast.config.QuotConfig;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * 反序列化
 */
//1.创建泛型反序列化类实现反序列化接口
public class AvroDeserializerSchema<T> implements DeserializationSchema<T> {
    private String topicName;


    //创造构造方法
    public  AvroDeserializerSchema(String topicName) {
        this.topicName = topicName;
    }

    //反序列化
    @Override
    public T deserialize(byte[] message) throws IOException {
        DatumReader<T> specificDatumWriter ;
        if (topicName.equals(QuotConfig.config.getProperty("sse.topic"))){
            specificDatumWriter= new SpecificDatumReader<>(new SseAvro().getSchema());
        }else {
            specificDatumWriter= new SpecificDatumReader<>(new SzseAvro().getSchema());
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(message);
        Decoder decoder = DecoderFactory.get().binaryDecoder(byteArrayInputStream, null);
        //第一个参数是 重试
        return specificDatumWriter.read(null,decoder);
    }

    @Override
    public boolean isEndOfStream(T nextElement) {
        return false;
    }
//获取序列化类型
    @Override
    public TypeInformation<T> getProducedType() {
        if (topicName.equals(QuotConfig.config.getProperty("sse.topic"))){
            return (TypeInformation<T>) TypeInformation.of(SseAvro.class);
        }else {
            return (TypeInformation<T>) TypeInformation.of(new TypeHint<SzseAvro>() {
            });
        }

    }
}
